#!/bin/bash
PEM=microservices-demo-key
STACK_NAME=microservices-demo-stack
ORG_FILE="$( cd $(dirname $0) ; pwd -P )/cloudformation.json"
TMP_FILE="/tmp/cloudformation.json"
CF_FILE="file://$TMP_FILE"
THIS_F=`basename "$0"`
WEAVETOKEN=$2
function build
{

	mkdir ~/.ssh/ &>/dev/null && chmod 700 ~/.ssh/

	if [ -e "~/.ssh/$PEM.pem" ]
	then
		printf "You already have an existing key ~/.ssh/$PEM.pem, you can either delete your pem or update this script and rename the PEM\n"
		exit
	fi


	aws ec2 describe-key-pairs --key-names $PEM &>/dev/null
	if [ $? -ne 0 ]; then
		printf "Key pair '$PEM' does not exist, creating\n"
	else
		printf "You already have an existing aws key pair '$PEM', you can either delete your aws key pair or update this script and rename the PEM\n"
		exit
	fi

	aws ec2 create-key-pair --key-name $PEM --query 'KeyMaterial' --output text > ~/.ssh/$PEM.pem
	chmod 600 ~/.ssh/$PEM.pem


	printf "Creating stack $STACK_NAME\n"
	  aws logs create-log-group --log-group-name $STACK_NAME
	  cat $ORG_FILE | jq -c '.' > $TMP_FILE
	  aws cloudformation create-stack \
		--stack-name $STACK_NAME \
		--template-body $CF_FILE \
		--capabilities CAPABILITY_IAM CAPABILITY_NAMED_IAM \
		--parameters ParameterKey=KeyName,ParameterValue=$PEM ParameterKey=WeaveCloudServiceToken,ParameterValue=$WEAVETOKEN
	printf "Stack has been started, you can run './$THIS_F status' to get an update on the status\n"
}

function updatestack
{
	cat $ORG_FILE | jq -c '.' > $TMP_FILE
	aws cloudformation update-stack \
		--stack-name $STACK_NAME \
		--template-body $CF_FILE \
		--capabilities CAPABILITY_IAM CAPABILITY_NAMED_IAM \
		--parameters ParameterKey=KeyName,ParameterValue=$PEM
}

function get_status
{
	printf "Stack Status:\n"
	while :
	do
		stat=$(aws cloudformation describe-stacks --stack-name $STACK_NAME  | jq -r '.Stacks[0].StackStatus' )
		case $stat in

	        	CREATE_IN_PROGRESS )	printf "Create in Progress\n"
						sleep 2
                                		;;
	
	        	DELETE_IN_PROGRESS )	printf "Destroy in Progress\n"
						sleep 2
                                		;;
	
		        CREATE_COMPLETE )	printf "Creation Complete\n"
						dnsend
						exit
                                		;;

		        DESTROY_COMPLETE )	printf "Destroy Complete\n"
						exit
                                		;;

			* )			printf "Unexpected status $stat\n"
						exit

		esac
	done

}

function dnsend
{
	elbr=$(aws cloudformation describe-stack-resources \
	       	--stack-name $STACK_NAME --logical-resource-id EcsFrontendElasticLoadBalancing \
		| jq -r '.StackResources[0].PhysicalResourceId' )
	elbdns=$(aws elb describe-load-balancers --load-balancer-name $elbr \
		| jq -r '.LoadBalancerDescriptions[0].DNSName' )
	albr=$(aws cloudformation describe-stack-resources \
                --stack-name $STACK_NAME --logical-resource-id EcsScopeApplicationLoadBalancing \
		| jq -r '.StackResources[0].PhysicalResourceId')
	albdns=$(aws elbv2 describe-load-balancers --load-balancer-arns $albr \
		| jq -r '.LoadBalancers[0].DNSName' )
	printf "Visit your site here: http://$elbdns\n"
	printf "Visit WeaveScope here if you are not using Weave Cloud: http://$albdns\n"
	elbr=$(aws cloudformation describe-stack-resources \
	       	--stack-name $STACK_NAME --logical-resource-id EcsZipkinElasticLoadBalancing \
		| jq -r '.StackResources[0].PhysicalResourceId' )
	elbdns=$(aws elb describe-load-balancers --load-balancer-name $elbr \
		| jq -r '.LoadBalancerDescriptions[0].DNSName' )
	printf "Visit Zipkin here: http://$elbdns:9411\n"
}

function loadtest
{
        aws cloudformation wait stack-create-complete --stack-name $STACK_NAME
        if [ $? -ne 0 ]; then
            echo "Failed to create stack."
            exit 1
        fi
	elbr=$(aws cloudformation describe-stack-resources \
	       	--stack-name $STACK_NAME --logical-resource-id EcsFrontendElasticLoadBalancing \
		| jq -r '.StackResources[0].PhysicalResourceId' )
	elbdns=$(aws elb describe-load-balancers --load-balancer-name $elbr \
		| jq -r '.LoadBalancerDescriptions[0].DNSName' )
	docker run weaveworksdemos/load-test -d 60 -h $elbdns -c 2 -r 50
}

function destroy
{
	printf "Requesting stack be destroyed\n"
	aws cloudformation delete-stack --stack-name $STACK_NAME
	aws logs delete-log-group --log-group-name $STACK_NAME
	printf "Deleting key pair '$PEM'\n"
	aws ec2 delete-key-pair --key-name $PEM
	printf "Removing pem file ~/.ssh/$PEM.pem\n"
	rm ~/.ssh/$PEM.pem
}

case $1 in
	        build )			build
					exit
                                	;;
	
	        destroy )		destroy
					exit
                                	;;

	        status )		get_status
					exit
                                	;;

	        dns )			dnsend
					exit
                                	;;

	        loadtest )		loadtest
					exit
                                	;;

	        updatestack )		updatestack
					exit
                                	;;

		* )			printf "Invalid Operation\n"
					exit
					;;

esac
